package ar.edu.itba.bundundu;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;

//import com.google.code.facebookapi.FacebookException;
import ar.edu.itba.bundundu.dao.UserDao;
import ar.edu.itba.bundundu.domain.UserIds;
import ar.edu.itba.bundundu.util.EventProperties;

import com.google.code.facebookapi.FacebookParam;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.calendar.CalendarEntry;
import com.google.gdata.data.calendar.CalendarFeed;
import com.google.gson.Gson;

public class EventsServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	  throws ServletException, IOException {
		RequestDispatcher dispatcher;
		Facebook fb;
		Long fbid;
		Object events;
		String error="";
		String err = (String)req.getAttribute("err");
		if(err!=null && !err.equals("")){
		  error = error + err;
		}

		dispatcher = getServletContext().getRequestDispatcher("/events.jsp");
		fb = new Facebook(req.getParameter(FacebookParam.SESSION_KEY.toString()));
		fbid = fb.getUserId();

		//para obtener los eventos de facebook
		try {		  
			events = fb.getClient().events_get(fbid, null, (new Date().getTime())/1000, null);
			if(  events.getClass() != org.json.JSONArray.class){
			  throw new Exception("You have no events :( ");
			}
			
			ArrayList<EventProperties> propsarray = new ArrayList<EventProperties>();
		   int i;
	      for (i = 0; i < ((JSONArray)events).length(); i++) {
	        Gson gson = new Gson();
	        String event = ((JSONArray)events).getString(i);
	        EventProperties props = new EventProperties();

	        props = gson.fromJson(event, EventProperties.class);

	        if(props.getPic() == null || props.getPic().equals(""))
	          props.setPic("http://static.ak.fbcdn.net/pics/s_default.jpg");

	        Calendar cal = Calendar.getInstance();
	        Date d = new Date((props.getStart_time()*1000)-(8*1000*60*60));
	        cal.setTime(d);
	        String mimes1;
	        if(cal.get(Calendar.MONTH)+1 < 10)
	          mimes1 = "0" + (cal.get(Calendar.MONTH)+1);
	        else
	          mimes1 = String.valueOf(cal.get(Calendar.MONTH)+1);

	        String fecha_inicio = cal.get(Calendar.YEAR) + "-" + mimes1 + "-"
	            + ((cal.get(Calendar.DAY_OF_MONTH))<10?"0":"")
	              + (cal.get(Calendar.DAY_OF_MONTH));
	        props.setFecha_inicio(fecha_inicio);
	        String hora_inicio = 
	          ((cal.get(Calendar.HOUR_OF_DAY))<10? "0":"")
	              + (cal.get(Calendar.HOUR_OF_DAY)) 
	            + ":" 
	            + (cal.get(Calendar.MINUTE)<10?"0":"")
	              + cal.get(Calendar.MINUTE);
	        props.setHora_inicio(hora_inicio);

	        d = new Date((props.getEnd_time()*1000)-(8*1000*60*60));
	        cal.setTime(d);
	        String mimes2;
	        if(cal.get(Calendar.MONTH)+1 < 10)
	          mimes2 = "0" + (cal.get(Calendar.MONTH)+1);
	        else
	          mimes2 = String.valueOf(cal.get(Calendar.MONTH)+1);
	        String fecha_fin = cal.get(Calendar.YEAR) + "-" + mimes2 + "-"
	            + ((cal.get(Calendar.DAY_OF_MONTH))<10?"0":"")
	              + (cal.get(Calendar.DAY_OF_MONTH));
	        props.setFecha_fin(fecha_fin);
	        String hora_fin =
	         ((cal.get(Calendar.HOUR_OF_DAY))<10? "0":"")
	            + (cal.get(Calendar.HOUR_OF_DAY)) 
	          + ":" 
	          + (cal.get(Calendar.MINUTE)<10? "0":"")
	            + cal.get(Calendar.MINUTE);
	        props.setHora_fin(hora_fin);
	        propsarray.add(props);
	      }
	      //TODO ordenar el array por fecha de inicio
			req.setAttribute("events", propsarray);
		} catch (Exception e) {
			req.setAttribute("events", null);
			req.setAttribute("error", e.getMessage());
		}
		
		//para obtener los calendarios de google
		try{
        UserIds user = UserDao.getUser(fbid);
        String sessionToken = user.getToken();
        CalendarService service = new CalendarService("exampleCo-exampleApp-1");
        service.setAuthSubToken(sessionToken, null);
    
        // levantar los calendarios de tipo "owner"
        ArrayList<CalendarEntry> calendars = new ArrayList<CalendarEntry>();
        URL feedUrl = new URL(
            "http://www.google.com/calendar/feeds/default/owncalendars/full");
        CalendarFeed resultFeed = service.getFeed(feedUrl, CalendarFeed.class);
        for (int i = 0; i < resultFeed.getEntries().size(); i++) {
          CalendarEntry entry = resultFeed.getEntries().get(i);
          calendars.add(i, entry);
          
        }
        req.setAttribute("calendars", calendars);
	  } catch (Exception e) {
      req.setAttribute("calendars", null);
      req.setAttribute("error", error + ((e.getMessage()==null)||(e.getMessage().equals(""))?"":e.getMessage()));
      //e.printStackTrace();
    }
	  
	  if(err!=null && !err.equals("")){
	    req.setAttribute("error", error);
	  }
		
	  dispatcher.forward(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
	  throws ServletException, IOException {
		doGet(req, resp);
	}
}
